import React from 'react'
import {Input, Button, message} from 'antd'
import {HOST} from '../../utils/request'
import protobuf from 'protobufjs'
import jsonProto from '../../../../../protobuf/'
import PutSong from '../put_song'
import styles from './index.less'

export default class Chat extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      list: [],
      value: '',
    }
    this.props = props;
    this.init();
  }

  render() {
    return (
      <div className={styles.container}>
        <div className={styles.chat}>
          {
            this.state.list.map((msg, i) => {
              if (msg.code !== 200) {
                return (
                  <div className={styles.radio} key={i}>
                    {msg.content}
                  </div>
                );
              }
              return (
                <div className={styles.message} key={i}>
                  <span>{msg.from}</span>
                  <p>{msg.content}</p>
                </div>
              );
            })
          }
        </div>
        <div className={styles.send}>
          <Input placeholder="输入聊天消息" value={this.state.value} onChange={this.change.bind(this)} />
          <Button type="primary" style={{margin:'5px 0 0'}} onClick={this.send.bind(this)}>发送</Button>
          <PutSong />
        </div> 
      </div>
    );
  }

  init() {
    const Root = protobuf.Root.fromJSON(jsonProto);
    this.root = Root.lookupType('ws.Data');
    this.ws = new WebSocket(`ws://${HOST}/ws/upgrade`);
    this.ws.onmessage = this.onmessage.bind(this);
  }

  onmessage(data) {
    const file = new FileReader()
    file.readAsArrayBuffer(data.data)
    file.onload = d => {
      const buf = d.target.result;
      const json = this.root.decode(new Uint8Array(buf))
      return this.format(json)
    }
  }

  format(msg) {
    if (msg.code === 119) {
      // 系统切歌
      return this.props.sysChange();
    }
    if (
      ![110,112,200,201,202].includes(msg.code)
    )
    return;
    msg.data &&  (msg.data = JSON.parse(msg.data));
    let _msg = {
      code: msg.code,
      from: msg.data.from
    };
    if (msg.code === 201) {
      _msg.content = `${msg.data.from}  发起切歌`;
      this.props.updateList();
    } else if (msg.code === 202) {
      _msg.content = `${msg.data.from}  点播了歌曲  ${msg.data.msg}`;
      this.props.updateList();
    } else if (msg.code === 200) {
      _msg.content = msg.data.msg;
    } else if (msg.code === 112) {
      this.pong();
      return;
    }
    if (_msg.content) {
      this.state.list.push(_msg);
      this.setState({
        list: this.state.list
      });
    }
  }

  change(e) {
    this.setState({
      value: (e.target.value || '').trim()
    });
  }

  pong() {
    const data = this.serialize({
      code: 110,
    });
    this.ws.send(data);
  }

  serialize(data) {
    return this.root.encode(
      this.root.create(data)
    ).finish();
  }

  send() {
    if (!this.state.value) {
      return message.error('请输入聊天消息');
    }
    const data = this.serialize({
      code: 200,
      msg: this.state.value
    });
    this.ws.send(data);
    this.setState({
      value: ''
    });
  }

}